package org.jsola.hr.service.excel;

import cn.hutool.core.lang.Validator;
import com.alibaba.excel.context.AnalysisContext;
import lombok.extern.slf4j.Slf4j;
import org.jsola.admin.vo.AreaReduceVO;
import org.jsola.common.BeanKit;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.FormatUtils;
import org.jsola.hr.common.RegUtils;
import org.jsola.hr.dto.ChannelAddDTO;
import org.jsola.hr.dto.excel.ChannelInfoImportDTO;
import org.jsola.hr.exception.HrException;
import org.jsola.hr.provider.IAdminProviderService;
import org.jsola.hr.query.ChannelGroupUserQuery;
import org.jsola.hr.query.ChannelQuery;
import org.jsola.hr.query.HrRoleQuery;
import org.jsola.hr.service.*;
import org.jsola.hr.vo.*;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author WU
 */
@Slf4j
public class ChannelInfoImportListener extends BaseAnalysisEventListener<ChannelInfoImportDTO> {

    /**
     * 导入渠道数据VO
     */
    protected ChannelImportExcelVO channelImportExcelVO = new ChannelImportExcelVO();
    /**
     * 必有表头字段
     */
    protected List<String> requiredHeadList = new ArrayList<>();

    /**
     * 导入成功的数据
     */
    protected List<ChannelInfoImportDTO> importSuc = new ArrayList<>();

    /**
     * 导入失败的数据
     */
    protected List<ChannelInfoImportDTO> importFil = new ArrayList<>();

    /**
     * true忽略错误的行，false有错误中断上传
     */
    protected Boolean force = true;

    /**
     * 导入失败的渠道信息
     */
    protected List<ChannelVO> failChannelList;

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        //校验表头
        requiredHeadList.add("所属分组");
        requiredHeadList.add("渠道名称");
        requiredHeadList.add("联系电话");
        List<String> headList = new ArrayList<>();
        for (Map.Entry<Integer, String> integerStringEntry : headMap.entrySet()) {
            headList.add(integerStringEntry.getValue());
        }
        for (String needHead : requiredHeadList) {
            ParamException.isTrue(headList.contains(needHead), "缺少必要表头：" + needHead);
        }
    }

    /**
     * 入库
     */
    @Override
    public void saveData() {
        log.info("{}条数据，开始存储数据库！", dataList.size());
        IAdminProviderService adminProviderService = BeanKit.getBean(IAdminProviderService.class);
        IChannelService channelService = BeanKit.getBean(IChannelService.class);
        IChannelGroupService channelGroupService = BeanKit.getBean(IChannelGroupService.class);
        IChannelGroupJurisdictionService channelGroupJurisdictionService = BeanKit.getBean(IChannelGroupJurisdictionService.class);
        List<AreaReduceVO> areaList = adminProviderService.listAllArea();
        if (dataList.size() == 0) {
            log.warn("没有数据需要入库");
            throw new ParamException("导入的数据为空，请检查模板中是否有内容");
        }
        for (int i = 0; i < dataList.size(); i++) {
            failChannelList = new ArrayList<>();
            String channelGroupId = "";
            ChannelInfoImportDTO channelInfoImportDTO = dataList.get(i);
            //校验分组名
            if (StringUtils.isEmpty(channelInfoImportDTO.getGroupName())) {
                channelInfoImportDTO.setErrorField("groupName");
                channelInfoImportDTO.setErrorReason("渠道分组：为空");
                importFil.add(channelInfoImportDTO);
                continue;
            }
            ChannelGroupVO channelGroupVO = channelGroupService.selectByChannelName(channelInfoImportDTO.getGroupName(), tokenUser);
            int jurisdiction = channelGroupJurisdictionService.getMyJurisdiction(tokenUser);
            if (channelGroupVO != null) {
                //本人是否是超级管理员或者租户总管理
                if (jurisdiction != 0 && jurisdiction != 2) {
                    ChannelGroupUserQuery channelGroupUserQuery = new ChannelGroupUserQuery();
                    channelGroupUserQuery.setUserId(tokenUser.getUserId());
                    channelGroupUserQuery.setGroupId(channelGroupVO.getId());
                    IChannelGroupUserService channelGroupUserService = BeanKit.getBean(IChannelGroupUserService.class);
                    List<ChannelGroupUserListVO> channelGroupUserListVOList = channelGroupUserService.select(channelGroupUserQuery, tokenUser.getSiteId());
                    if (CollectionUtils.isEmpty(channelGroupUserListVOList)) {
                        channelInfoImportDTO.setErrorField("groupName");
                        channelInfoImportDTO.setErrorReason("该分组不存在，请重新导入");
                        importFil.add(channelInfoImportDTO);
                        continue;
                    }
                }
                channelGroupId = channelGroupVO.getId();
            } else {
                if ("默认分组".equals(channelInfoImportDTO.getGroupName())) {
                    if (jurisdiction == 0 || jurisdiction == 1 || jurisdiction == 2) {
                        channelGroupId = "DEFAULT";
                    }
                } else {
                    channelInfoImportDTO.setErrorField("groupName");
                    channelInfoImportDTO.setErrorReason("该分组不存在，请重新导入");
                    importFil.add(channelInfoImportDTO);
                    continue;
                }
            }
            //校验渠道名
            if (StringUtils.isEmpty(channelInfoImportDTO.getName())) {
                channelInfoImportDTO.setErrorField("name");
                channelInfoImportDTO.setErrorReason("渠道名称：为空");
                importFil.add(channelInfoImportDTO);
                continue;
            }
            //校验电话
            if (StringUtils.isEmpty(channelInfoImportDTO.getPhone())) {
                channelInfoImportDTO.setErrorField("phone");
                channelInfoImportDTO.setErrorReason("联系电话：为空");
                importFil.add(channelInfoImportDTO);
                continue;
            } else {
                if (!Validator.isMobile(channelInfoImportDTO.getPhone())) {
                    channelInfoImportDTO.setErrorField("phone");
                    channelInfoImportDTO.setErrorReason("联系电话：格式有误");
                    importFil.add(channelInfoImportDTO);
                    continue;
                }
                ChannelQuery channelQuery = new ChannelQuery();
                channelQuery.setPhone(channelInfoImportDTO.getPhone());
                List<ChannelListVO> select = channelService.select(channelQuery, tokenUser.getSiteId());
                if (!CollectionUtils.isEmpty(select)) {
                    channelInfoImportDTO.setErrorField("phone");
                    channelInfoImportDTO.setErrorReason("联系电话：已存在");
                    importFil.add(channelInfoImportDTO);
                    continue;
                }
            }
            //校验地区
            String city = null;
            if (!StringUtils.isEmpty(channelInfoImportDTO.getAddress())) {
                city = FormatUtils.checkCity1(channelInfoImportDTO.getAddress(), areaList);
                if (city == null) {
                    channelInfoImportDTO.setErrorField("address");
                    channelInfoImportDTO.setErrorReason("所在地区：格式有误，请参考模板批注");
                    importFil.add(channelInfoImportDTO);
                    continue;
                }
            }
            //校验身份证
            if (!StringUtils.isEmpty(channelInfoImportDTO.getIdcard())) {
                if (!RegUtils.isIdCardAllType(channelInfoImportDTO.getIdcard())) {
                    channelInfoImportDTO.setErrorField("idcard");
                    channelInfoImportDTO.setErrorReason("身份证号：格式有误");
                    importFil.add(channelInfoImportDTO);
                    continue;
                } else {
                    ChannelVO channelVO = channelService.selectByIdCard(channelInfoImportDTO.getIdcard(), tokenUser);
                    if (channelVO != null && channelVO.getId() != null) {
                        channelInfoImportDTO.setErrorField("idcard");
                        channelInfoImportDTO.setErrorReason("身份证号：已存在");
                        importFil.add(channelInfoImportDTO);
                        continue;
                    }
                }
            }
            ChannelAddDTO channelAddDTO = channelInfoImportDTO.to(ChannelAddDTO.class);
            HrException.notNull(tokenUser, "没有设置当前登录用户");
            // 查询人力角色id
            IHrRoleService hrRoleService = BeanKit.getBean(IHrRoleService.class);
            HrRoleQuery hrRoleQuery = new HrRoleQuery();
            hrRoleQuery.setName("渠道");
            List<HrRoleListVO> hrRoleListVOList = hrRoleService.selectAndInitialization(hrRoleQuery, tokenUser);
            ParamException.isFalse(CollectionUtils.isEmpty(hrRoleListVOList),
                    "当前角色名称中没有渠道，请前往角色管理添加角色名称为：渠道 的角色");
            // 设置初始值
            channelAddDTO.setUserName(channelAddDTO.getName());
            channelAddDTO.setHrRoleId(hrRoleListVOList.get(0).getId());
            channelAddDTO.setIsAllChildCompany(true);
            channelAddDTO.setPassword("123456");
            channelAddDTO.setChannelGroupId(channelGroupId);
            channelAddDTO.setAddress(city);
            ChannelVO channelVO = channelService.save(channelAddDTO, false, tokenUser);
            if (Objects.nonNull(channelVO)) {
                importSuc.add(channelInfoImportDTO);
                successCount++;
            } else {
                channelInfoImportDTO.setErrorField("name");
                channelInfoImportDTO.setErrorReason("渠道名称：已存在");
                importFil.add(channelInfoImportDTO);
                ChannelVO failChannelVO = new ChannelVO();
                failChannelVO.setName(channelAddDTO.getName());
                failChannelVO.setPhone(channelAddDTO.getPhone());
                failChannelList.add(failChannelVO);
            }
        }
        channelImportExcelVO.setImportFil(importFil);
        channelImportExcelVO.setImportSuc(importSuc);
        log.info("存储数据库成功！");
    }

    public ChannelImportExcelVO getChannelImportExcelVO() {
        return channelImportExcelVO;
    }

    public List<ChannelVO> getFailChannelList() {
        return failChannelList;
    }
}
